﻿using DeviceFaultPushService;
using DeviceFaultPushService.DeviceProcessManagement.CommunicationManagement.Models;
using DeviceFaultPushService.SystemService;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;

//图标 https://iconpark.oceanengine.com/home

namespace 设备报警推送服务
{
    public partial class 主页 : Form
    {
        public 主页()
        {
            InitializeComponent();
        }

        #region 显示行号
        private void dtLineHCurvePara_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                var grid = sender as DataGridView;
                var rowidx = (e.RowIndex).ToString();
                var centerFormat = new StringFormat()
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                };
                var headerBuunds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid!.RowHeadersWidth, e.RowBounds.Height);
                e.Graphics.DrawString(rowidx, new Font("宋体", 11), SystemBrushes.ControlText, headerBuunds, centerFormat);
            }
            catch (Exception)
            {

            }

        }
        #endregion

        private void btnClean_Click(object sender, EventArgs e)
        {
            tbLog.Text = "";
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            if (this.Height == 780)
            {
                this.Height = 548;
                btnClean.Visible = false;
            }
            else if (this.Height == 548)
            {
                this.Height = 780;
                btnClean.Visible = true;
            }
        }
        StartUp runService = new();
        private void 主页_Load(object sender, EventArgs e)
        {
            ConfigService configService = new ConfigService();
            string result = configService.GetCompileVersion();
            if (result.Length >= 6) // 确保字符串至少有6个字符，以便可以安全地删除首尾各两位数  
            {
                result = result.Substring(2, result.Length - 4); // 从第3个字符开始，取长度为原字符串长度减4的子字符串   
            }
            int len = result.Length;
            if (len % 2 == 0) // 确保字符串的长度是偶数，以便可以安全地每两位加入间隔  
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < len; i += 2)
                {
                    sb.Append(result.Substring(i, 2)); // 取出每两位数字  
                    if (i + 2 < len) // 如果不是最后两位，则加入间隔  
                    {
                        sb.Append(".");
                    }
                }
                labelVer.Text = $"Ver : {sb.ToString()}";
            }

            // 假设你的DataGridView控件名为dataGridView1  
            dataGridView1.DefaultCellStyle.Font = new Font("Microsoft YaHei UI", 10F);

            //设置DataGridView文本居中
            dataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //标题文字居中.
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //行高设置
            dataGridView1.RowTemplate.Height = 30;
            dataGridView1.RowTemplate.MinimumHeight = 30;

            runService.CloseEvent += CloseEvents;
            runService.RunningEvent += RunningEvents;
            runService.LogEvent += AppText;

            ArrayList arrayList = ConfigService.GetID();

            if (arrayList is null)
            {
                return;
            }
            dataGridView1.Rows.Clear();
            int num = 0;
            foreach (string item in arrayList)
            {
                int index = dataGridView1.Rows.Add();
                string readText = File.ReadAllText($"json/{item}.json");
                DeviceInformationModel di = JsonSerializer.Deserialize<DeviceInformationModel>(readText)!;

                dataGridView1.Rows[index].Cells[0].Value = di.Number;
                dataGridView1.Rows[index].Cells[1].Value = di.Name;
                dataGridView1.Rows[index].Cells[2].Value = "编辑";
                if (runService.RunningId.Contains(item))
                {
                    dataGridView1.Rows[index].Cells[3].Value = DateTime.Now;
                    dataGridView1.Rows[index].Cells[4].Value = "关闭";
                }
                else
                {
                    dataGridView1.Rows[index].Cells[3].Value = "";
                    dataGridView1.Rows[index].Cells[4].Value = "激活";
                }
                num++;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddDevice_Click(object sender, EventArgs e)
        {
            if (new 特殊验证服务().ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Form form = new 设备添加与调整();
            form.ShowDialog();

            //刷新页面
            ArrayList arrayList = ConfigService.GetID();

            if (arrayList is null)
            {
                return;
            }
            dataGridView1.Rows.Clear();
            int num = 0;
            foreach (string item in arrayList)
            {
                int index = dataGridView1.Rows.Add();
                string readText = File.ReadAllText($"json/{item}.json");
                DeviceInformationModel di = JsonSerializer.Deserialize<DeviceInformationModel>(readText)!;

                dataGridView1.Rows[index].Cells[0].Value = di.Number;
                dataGridView1.Rows[index].Cells[1].Value = di.Name;
                dataGridView1.Rows[index].Cells[2].Value = "编辑";
                if (runService.RunningId.Contains(item))
                {
                    dataGridView1.Rows[index].Cells[3].Value = DateTime.Now;
                    dataGridView1.Rows[index].Cells[4].Value = "关闭";
                }
                else
                {
                    dataGridView1.Rows[index].Cells[3].Value = "";
                    dataGridView1.Rows[index].Cells[4].Value = "激活";
                }
                num++;
            }

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //按钮事件 5
                DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                if (e.ColumnIndex == 4)
                {
                    if (row.Cells[4].Value is null)
                    {
                        return;
                    }
                    string cellValue = row.Cells[4].Value.ToString()!;

                    if (cellValue == "关闭")
                    {
                        //关闭报警服务 
                        Form form = new 验证服务();

                        DialogResult dialogResult = form.ShowDialog();

                        if (dialogResult != DialogResult.OK)
                        {
                            return;
                        }
                        //关闭报警服务 
                        runService.Stop(row.Cells[0].Value.ToString());
                    }
                    if (cellValue == "激活")
                    {
                        // 开启报警服务
                        runService.Run(row.Cells[0].Value.ToString());
                    }
                }
                //编辑配 3
                if (e.ColumnIndex == 2)
                {
                    if (new 特殊验证服务().ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    //检查按钮是否有值
                    if (row.Cells[2].Value is null)
                    {
                        return;
                    }
                    string cellValue = row.Cells[2].Value.ToString()!;

                    if (cellValue != "编辑")
                    {
                        return;
                    }
                    //实例化配置编辑页面
                    string str = File.ReadAllText($"json/{row.Cells[0].Value}.json");

                    Form form = new 设备添加与调整(str);

                    var dialogResult = form.ShowDialog();

                    if (dialogResult == DialogResult.OK)
                    {
                        //保存新的配置文件，重启服务
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 系统配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSystemConfiguration_Click(object sender, EventArgs e)
        {
            if (new 特殊验证服务().ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Form form = new 系统配置();
            form.ShowDialog();
            runService.InitializeService();

        }

        /// <summary>
        /// 运行id事件
        /// </summary>
        private void CloseEvents(string id)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                string s = dataGridView1.Rows[i].Cells[0].Value.ToString()!;

                if (s == id)
                {
                    dataGridView1.Rows[i].Cells[3].Value = "";
                    dataGridView1.Rows[i].Cells[4].Value = "激活";
                }
            }
        }

        /// <summary>
        /// 日志操作
        /// </summary>
        /// <param name="str"></param>
        public void AppText(string str)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    str = $"[{DateTime.Now.ToString("f")}]    {str}\r\n";
                    tbLog.AppendText(str);
                    notifyIcon.ShowBalloonTip(5000, "设备通知", str, ToolTipIcon.Info); // 显示气球提示（可选） 
                }));
            }
            catch (Exception)
            {

            }
        }

        private void RunningEvents(string id)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                string s = dataGridView1.Rows[i].Cells[0].Value.ToString()!;

                if (s == id)
                {
                    dataGridView1.Rows[i].Cells[3].Value = DateTime.Now.ToString("F");
                    dataGridView1.Rows[i].Cells[4].Value = "关闭"; ;
                }
            }
        }

        private void 主页_FormClosing(object sender, FormClosingEventArgs e)
        {
            //退出验证服务
            Form form = new 验证服务();

            DialogResult dialogResult = form.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                e.Cancel = false;
                Environment.Exit(0);
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void 主页_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                foreach (var item in runService.RunningId)
                {
                    runService.Stop(item);

                    Thread.Sleep(1000);
                }
            }
            catch (Exception)
            {

            }

        }

        private void notifyIcon_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
            else if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void 主页_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide(); // 隐藏窗体 
            }
        }
    }
}
